﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Board : MonoBehaviour {

    public GameObject CrossPrefab;

    const float CrossSize = 40;//cross尺寸

    public const int CrossCount = 15;

    public const int Size = 560;

    public const int HalfSize = Size / 2;

    Dictionary<int, Cross> _crossMap = new Dictionary<int, Cross>();

    static int MakeKey(int x, int y)
    {
        return x * 1000 + y;
    }

    public void Reset()
    {

        foreach (Transform child in gameObject.transform)
        {
            GameObject.Destroy(child.gameObject);
        }

        MainLoop mainLoop = GetComponent<MainLoop>();

        _crossMap.Clear();
        for (int x = 0; x < CrossCount; x++)
        {
            for (int y = 0; y < CrossCount; y++)
            {
                //生成Cross预制物
                GameObject crossObject = GameObject.Instantiate(CrossPrefab);
                //给Cross绑定父级
                crossObject.transform.SetParent(gameObject.transform);
                //给Cross设定缩放
                crossObject.transform.localScale = Vector3.one;
                //获取Cross的自身坐标(相对于父级物体)
                Vector3 pos = crossObject.transform.localPosition;
                //设定Cross的自身坐标的X
                pos.x = -HalfSize + x * CrossSize;

                pos.y = -HalfSize + y * CrossSize;

                pos.z = 1;

                crossObject.transform.localPosition = pos;

                Cross cross = crossObject.GetComponent<Cross>();

                cross.GridX = x;
                cross.GridY = y;
                cross._mainLoop = mainLoop;

                _crossMap.Add(MakeKey(x,y),cross);
            }
        }
    }

    public Cross GetCross(int gridX, int gridY)
    {
        Cross cross;
        if (_crossMap.TryGetValue(MakeKey(gridX,gridY),out cross))
        {
            return cross;
        }
        return null;
    }
	// Use this for initialization
	void Start () {
        Reset();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
